//
//  HTMoodViewController.m
//  HappyTravel
//
//  Created by Apple on 2018/8/2.
//  Copyright © 2018年 Apple. All rights reserved.
//

#import "HTMoodViewController.h"
#import "HTMoodTableViewCell.h"
#import "HTModel.h"
#import "HTAddMoodViewController.h"
#import <PGDatePicker/PGDatePickManager.h>

@interface HTMoodViewController () <UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource,PGDatePickerDelegate>

@property (nonatomic, strong) UITextField *dropDownTextField;
@property (nonatomic, strong) UIButton *editBtn;
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *travelLogArr;
@property (nonatomic, strong) NSMutableArray *dataArr;

@end

@implementation HTMoodViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    self.tabBarController.tabBar.hidden = NO;
    self.navigationController.navigationBar.barTintColor = ThemeColor;
    [[UIApplication sharedApplication] setStatusBarStyle:(UIStatusBarStyleLightContent)];
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:18],NSForegroundColorAttributeName:COLOR_RGB(255, 255, 255)}];
    
    [self loadData];

}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    
    [self loadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"Travel log";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupUI];
}

#pragma mark - CustomMethod
- (void)loadData {
    
    [self.travelLogArr removeAllObjects];
    self.travelLogArr = [HTSingleton readModelArrayForDocument:AblumModelPath];
    [self comapreWithMonth:self.dropDownTextField.text];
    [self.tableView reloadData];
}

- (void)comapreWithMonth:(NSString *)date{
    
    [self.dataArr removeAllObjects];
    for (HTModel *model in self.travelLogArr) {
        int  comapre = [self comapreDate:date anotherDate:model.currentTime andFormat:@"yyyy-MM"];
        if (comapre == 0){
            [self.dataArr addObject:model];
        }
    }
}


-(int )comapreDate:(NSString *)date anotherDate:(NSString *)anotherDate andFormat:(NSString *)format{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    NSDate *dates = [dateFormatter dateFromString:date];
    anotherDate = [anotherDate substringWithRange:NSMakeRange(0, 7)];
    NSDate *another = [dateFormatter dateFromString:anotherDate];
    
    NSComparisonResult result = [dates compare:another];
    if (result == NSOrderedDescending) {
        return 1;
    }else if(result ==NSOrderedSame){
        return 0;
    }else {
        return -1;
    }
}


- (void)setupUI {
    
    [self.view addSubview:self.dropDownTextField];
    [self.view addSubview:self.editBtn];
    [self.view addSubview:self.tableView];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {

    PGDatePickManager *datePickManager = [[PGDatePickManager alloc]init];
    PGDatePicker *datePicker = datePickManager.datePicker;
    datePicker.datePickerMode = PGDatePickerModeYearAndMonth;
    datePicker.rowHeight = 40;
    datePicker.delegate = self;
    [self presentViewController:datePickManager animated:false completion:nil];
    
    return NO;
}

#pragma mark - PGDatePickerDelegate
- (void)datePicker:(PGDatePicker *)datePicker didSelectDate:(NSDateComponents *)dateComponents {
    
    self.dropDownTextField.text = [NSString stringWithFormat:@"%ld-%ld",(long)dateComponents.year,(long)dateComponents.month];
    [self loadData];
}

#pragma mark - UITableViewDelegate && UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identifier = @"HTMoodTableViewCell";
    HTMoodTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (!cell) {
        cell = [[HTMoodTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    cell.backgroundColor = [UIColor whiteColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    HTModel *model = self.dataArr[indexPath.row];
    
    if (indexPath.row == 0) {
        cell.imagePortrait.image = [UIImage imageNamed:@"firstMood"];
    }else {
        cell.imagePortrait.image = [UIImage imageNamed:@"nextMood"];
    }
    
    cell.model = model;
    cell.deleteBtn.tag = indexPath.row;
    cell.didClickDeleteBlock = ^(UIButton *button) {
        HTModel *model = self.dataArr[button.tag];
        [self.travelLogArr removeObject:model];
        [HTSingleton saveModelDictionaryInDocument:self.travelLogArr andPath:AblumModelPath];
        [self loadData];
    };
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    HTModel *model = self.travelLogArr[indexPath.row];
    return model.rowHeight;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

#pragma makr - touches events
- (void)actionOfClickEditBtn {
    
    HTAddMoodViewController *addVc = [[HTAddMoodViewController alloc]init];
    [self.navigationController pushViewController:addVc animated:YES];
}

#pragma mark - getter
- (UITextField *)dropDownTextField {
    return _dropDownTextField ?: ({
        _dropDownTextField = [[UITextField alloc]initWithFrame:CGRectMake(30, 15+SafeAreaTopHeight, 100, 30)];
        _dropDownTextField.text = [HTSingleton getCurrentMonth];
        _dropDownTextField.textColor = UIColorOfHex(0x999999);
        _dropDownTextField.textAlignment = NSTextAlignmentCenter;
        _dropDownTextField.font = [UIFont systemFontOfSize:14];
        _dropDownTextField.delegate = self;
        
        UIButton *dropBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 16)];
        [dropBtn setImage:[UIImage imageNamed:@"drop"] forState:UIControlStateNormal];
        _dropDownTextField.rightView = dropBtn;
        _dropDownTextField.rightViewMode = UITextFieldViewModeAlways;
        
        _dropDownTextField.layer.borderColor = UIColorOfHex(0x999999).CGColor;
        _dropDownTextField.layer.borderWidth = 1.0f;
        _dropDownTextField.layer.cornerRadius = 10;
        _dropDownTextField;
    });
}

- (UIButton *)editBtn {
    return _editBtn ?: ({
        _editBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _editBtn.frame = CGRectMake(CGRectGetMaxX(self.view.bounds)-56, 19+SafeAreaTopHeight, 26, 26);
        [_editBtn setBackgroundImage:[UIImage imageNamed:@"edit"] forState:UIControlStateNormal];
        [_editBtn addTarget:self action:@selector(actionOfClickEditBtn) forControlEvents:UIControlEventTouchUpInside];
        _editBtn;
    });
}

- (UITableView *)tableView {
    return _tableView ?: ({
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.dropDownTextField.frame)+30, ScreenWidth, ScreenHeight-TabbarHeight-SafeAreaTopHeight-75) style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
//        _tableView.estimatedRowHeight = 200;
//        _tableView.rowHeight = UITableViewAutomaticDimension;
        [_tableView registerClass:[HTMoodTableViewCell class] forCellReuseIdentifier:@"HTMoodTableViewCell"];
        _tableView;
    });
}

- (NSMutableArray *)travelLogArr {
    if (!_travelLogArr) {
        _travelLogArr = [[NSMutableArray alloc] init];
    }
    return _travelLogArr;
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc] init];
    }
    return _dataArr;
}






@end
